package com.turingoal.common.util.spring;

import org.atmosphere.cpr.AtmosphereFramework;
import org.atmosphere.cpr.AtmosphereObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * AtomsphereSpringObjectFactory
 */
public class AtomsphereSpringObjectFactory implements AtmosphereObjectFactory {
	private final Logger logger = LoggerFactory.getLogger(AtomsphereSpringObjectFactory.class);

	/**
	 * newClassInstance
	 */
	@SuppressWarnings({ "unchecked", "resource" })
	@Override
	public <T, U extends T> U newClassInstance(final AtmosphereFramework framework, final Class<T> classType, final Class<U> classToInstantiate) throws InstantiationException, IllegalAccessException {
		ApplicationContext context = new AnnotationConfigApplicationContext(classToInstantiate);
		U t = context.getBean(classToInstantiate);
		if (t == null) {
			logger.info("Unable to find {}. Creating the object directly.", classToInstantiate.getName());
			return classToInstantiate.newInstance();
		}
		return t;
	}

	/**
	 * toString
	 */
	public String toString() {
		return "Spring ObjectFactory";
	}

}
